//
//  ImgView.swift
//  MD5
//
//  Created by 郑东喜 on 2016/11/24.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit


class ImgView: UIViewController,WKUIDelegate,WKScriptMessageHandler{
    /*! @abstract Invoked when a script message is received from a webpage.
     @param userContentController The user content controller invoking the
     delegate method.
     @param message The script message received.
     */
    @available(iOS 8.0, *)
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }


    var webView: WKWebView!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        var webView = WKWebView()
        
        //wkwebview相关配置
        
        
        //创建并配置WKWebView的相关参数
        //1.WKWebViewConfiguration:是WKWebView初始化时的配置类，里面存放着初始化WK的一系列属性；
        //2.WKUserContentController:为JS提供了一个发送消息的通道并且可以向页面注入JS的类，WKUserContentController对象可以添加多个scriptMessageHandler；
        //3.addScriptMessageHandler:name:有两个参数，第一个参数是userContentController的代理对象，第二个参数是JS里发送postMessage的对象。添加一个脚本消息的处理器,同时需要在JS中添加，window.webkit.messageHandlers.<name>.postMessage(<messageBody>)才能起作用。
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        
        
        configuration.userContentController = userContentController
        
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        webView.uiDelegate = self
        
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        //本地加载
        let htmlPath = Bundle.main.path(forResource: "WKWebViewMessageHandler", ofType: "html")
        
        
        do {
            let fileURL = try NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
            let baseURL = NSURL.fileURL(withPath: htmlPath! as String)
            webView.loadHTMLString(fileURL as String, baseURL: baseURL)
        } catch  {
            
        }
        
        if let path = Bundle.main.path(forResource: "ico", ofType: "jpg") {
            if let data = NSData(contentsOfFile: path) {
                if #available(iOS 9.0, *) {
                    webView.load(data as Data, mimeType: "image/jpeg",
                                 characterEncodingName: "", baseURL: NSURL(string: "")! as URL)
                } else {
                    // Fallback on earlier versions
                }
            }
        }
        
        view.addSubview(webView)
    }
}

